package com.example.baseapp.controller;

import com.example.baseapp.common.ApiResponse;
import com.example.baseapp.common.OrderStatusEnum;
import com.example.baseapp.entity.OrderInfo;
import com.example.baseapp.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;

@RestController
@RequestMapping("/admin/order")
public class AdminOrderController {
    
    private static final Logger logger = LoggerFactory.getLogger(AdminOrderController.class);
    
    @Autowired
    private OrderService orderService;
    
    // 更新订单状态
    @PostMapping("/updateStatus")
    public ApiResponse<OrderInfo> updateOrderStatus(@RequestBody Map<String, Object> params) {
        String orderNo = params.get("orderNo").toString();
        String newStatus = params.get("status").toString();
        
        logger.info("更新订单状态，订单号: {}, 新状态: {}", orderNo, newStatus);
        
        // 验证状态是否有效
        if (!isValidStatus(newStatus)) {
            return ApiResponse.error("无效的订单状态: " + newStatus);
        }
        
        try {
            OrderInfo updatedOrder = orderService.updateOrderStatus(orderNo, newStatus);
            if (updatedOrder == null) {
                return ApiResponse.error("订单不存在");
            }
            return ApiResponse.success(updatedOrder);
        } catch (Exception e) {
            logger.error("更新订单状态失败", e);
            return ApiResponse.error("更新订单状态失败: " + e.getMessage());
        }
    }
    
    // 获取所有可用状态
    @GetMapping("/statuses")
    public ApiResponse<Map<String, String>> getAllStatuses() {
        return ApiResponse.success(OrderStatusEnum.getStatusMap());
    }
    
    // 验证状态是否有效
    private boolean isValidStatus(String status) {
        String[] validStatuses = OrderStatusEnum.getAllStatuses();
        for (String validStatus : validStatuses) {
            if (validStatus.equals(status)) {
                return true;
            }
        }
        return false;
    }
} 